﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HelfenHelfen.DataAccess.Interfaces;
using HelfenHelfen.DataAccess.Entities;
using HelfenHelfen.DataAccess.Extensions;

namespace HelfenHelfen.DataAccess
{
    public class BonusItemDataAccess : IBonusItemDataAccess
    {

        #region IBonusItemDataAccess Members

        public BonusItem Insert(BonusItem newBonusItem)
        {
            using (HelfenHelfenEntities db = new HelfenHelfenEntities())
            {
                //TODO: At the moment the database field for the BonusItemGUID is not an autowert
                //so we set at the moment the GUID by code - this should be fixed in the database!
                newBonusItem.BonusItemGUID = Guid.NewGuid();
                db.BonusItems.AddObject(newBonusItem);
                db.SaveChanges();
            }
            return newBonusItem;
        }

        public void Delete(Guid bonusItemId)
        {
            using (HelfenHelfenEntities db = new HelfenHelfenEntities())
            {
                var originalBonusItem =     (from b in db.BonusItems
                                            where b.BonusItemGUID == bonusItemId
                                            select b).FirstOrDefault();

                if (originalBonusItem != null)
                {
                    db.DeleteObject(originalBonusItem);
                    db.SaveChanges();
                }
            }
        }

        public BonusItem Update(BonusItem updateBonusItem)
        {
            using (HelfenHelfenEntities db = new HelfenHelfenEntities())
            {
                var originalBonusItem = (from b in db.BonusItems
                                         where b.BonusItemGUID == updateBonusItem.BonusItemGUID
                                         select b).FirstOrDefault();

                db.BonusItems.Attach(originalBonusItem);
                db.BonusItems.ApplyCurrentValues(updateBonusItem);
                db.SaveChanges();
            }
            return updateBonusItem;
        }

        public BonusItem Get(Guid bonusItemId)
        {
            using (HelfenHelfenEntities db = new HelfenHelfenEntities())
            {
                return (from b in db.BonusItems.Include(b=>b.Organisation)
                        where b.BonusItemGUID == bonusItemId
                        select b).FirstOrDefault();
            }
        }

        public IList<BonusItem> GetAll()
        {
            using (HelfenHelfenEntities db = new HelfenHelfenEntities())
            {
                return db.BonusItems.Include(b=>b.Organisation).ToList();
            }
        }

        #endregion
    }
}
